<?php

namespace app\api\controller;


use think\Db;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use app\api\controller\My;
use addons\mplogin\model\Key;
use think\Cache;
use fast\Http;
use app\admin\model\caiwu\Money;

/**
 * 微信方法
 */
class Wechat
{

    /**
     * 获取授权链接
     */
    public static function config()
    {
        $config_open = [
            'app_id'   => 'wxc4cdcebced6e215d',
            'secret'   => '529c0214213ba1a2055231cb3f56f627',
            'token'    => 'token52156458784512121212',
            'aes_key'  => 'WFrNNmUcxnBTcrlFWyEkmtsasPEziuQdPHJclJbqcAq'
        ];
        return $config_open;
    }
    /**
     * 创建试用小程序
     */
    public function authorizer_refresh_token()
    {
        $config = self::config();
        $openPlatform = Factory::openPlatform($config);


        $response = $openPlatform->httpPostJson('/cgi-bin/component/api_authorizer_token', [
            "component_appid" => "wxc4cdcebced6e215d",
            "authorizer_appid" => "wxc4cf6d2f0e8717d1",
            "authorizer_refresh_token" => "refreshtoken@@@kIndLPQedqoMKiQA5Xq9UY9rCYou7o_AghPtmECfhpk",

        ]);
        return json($response);
    }
    /**
     * 试用认证
     */
    public function verfifyBetaMiniprogram()
    {
        $headers = ['Content-type: application/json'];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];
        $data = '{"verify_info":{"enterprise_name":"河南八恩科技有限公司","code":"91411103MAD4J3KY1C","code_type":1,"legal_persona_wechat":"ppppue","legal_persona_name":"杨兵涛","component_phone":"18838000395","legal_persona_idcard":"411123199405126516"}}';

        return http::post('https://api.weixin.qq.com/wxa/verifybetaweapp?access_token=75_0Bww2hPKkFOBmHf1HTJmoZRgjo64SE2fpzA3oTIoJVYSJ3imkqy35svMkzi_MUt-86ymMLa5vfEv_4S9xv2f6mkmpOhtOYZ6B8-9O-ogxwonglinGcvGdIpO9nyeaoso-F4ixRzksjLbeZqVHLOhALDVZC', $data, $options);
    }
    /**
     * 改名
     */
    public function modifyBetaMiniprogramNickName()
    {
        $headers = ['Content-type: application/json'];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];
        $data = '{"name":"八宝惠"}';

        return http::post('https://api.weixin.qq.com/wxa/setbetaweappnickname?access_token=75_piXPaRJT2nltTBfejDQSlnuAf1BbsVIqWqzGc7fkb1R0u9fSl5KADEI8glkRXejWaAAQZTZAl_FgMOdDE28A9nugh2Y5LLafwQLLOJ2t06LRs8qfxtM-5ocqvWTI8aMJcMSPXMhxK3A1VQk5UKAjAEDXND', $data, $options);
    }
    /**
     * 创建试用小程序
     */
    public function registerBetaMiniprogram()
    {
        $config = self::config();
        $openPlatform = Factory::openPlatform($config);


        $response = $openPlatform->httpPostJson('/wxa/component/fastregisterbetaweapp', [
            "name" => "八宝汇+",
            "openid" => "oEz4X6YvaVeINTvQ31UIsBO3A1w8",

        ]);
        return json($response);
    }
    /**
     * 创建小程序
     */
    public function fastregisterweapp()
    {
        $config = self::config();
        $openPlatform = Factory::openPlatform($config);




        $response = $openPlatform->httpPostJson('/cgi-bin/component/fastregisterweapp', [
            "name" => "河南八恩科技有限公司",
            "code" => "91411103MAD4J3KY1C",
            "code_type" => "1",
            "legal_persona_wechat" => "ppppue",
            'legal_persona_name' => '杨兵涛',
            'component_phone' => '18838000395'
        ], ['action' => 'create']);
        return json($response);
    }

    /**
     * 查询小程序
     */
    public static function queryStatus()
    {
        return [
            '100001' => '已超时',
            '100002' => '已超时',
            '100003' => '已超时',
            '101' => '企业已注销',
            '102' => '企业不存在',
            '103' => '法人信息有误',
            '104' => '法人信息有误',
            '105' => '法人信息有误',
            '1000' => '企业信息有误',
            '1001' => '主体上限',
            '1002' => '主体黑名单',
            '1003' => '管理员上限',
            '1004' => '管理员黑名单',
            '1005' => '管理员手机上限',
            '1006' => '管理员手机黑名单',
            '1007' => '管理员上限',
            '1008' => '管理员黑名单',
            '-1' => '信息不一致',
            '89249' => '任务执行中',
            '89247' => '系统内部错误',
            '86004' => '无效微信号',
            '61070' => '法人姓名与微信号不一致',
            '89251' => '已提交',
            '89252' => '信息校验中',
            '89255' => '信用代码有误',
        ];
    }

    /**
     * 查询小程序
     */
    public function fastregisterweappsearch()
    {
        $config = self::config();
        $openPlatform = Factory::openPlatform($config);

        $response = $openPlatform->httpPostJson('/cgi-bin/component/fastregisterweapp', [
            "name" => "河南八恩科技有限公司",
            "legal_persona_wechat" => "ppppue",
            'legal_persona_name' => '杨兵涛',
        ], ['action' => 'search']);
        return json($response);
    }
    /**
     * 获取授权链接
     */
    public static function getPreAuthorizationUrl($url)
    {
        $config = self::config();

        $openPlatform = Factory::openPlatform($config);
        return $openPlatform->getPreAuthorizationUrl($url); // 传入回调URI即可
    }
    /**
     * 获取授权
     */
    public static function handleAuthorize($authCode)
    {
        $config = self::config();

        $openPlatform = Factory::openPlatform($config);
        return $openPlatform->handleAuthorize($authCode); // 传入回调URI即可
    }
    /**
     * 获取授权
     */
    public static function getAuthorizer($authCode)
    {
        $config = self::config();

        $openPlatform = Factory::openPlatform($config);
        return $openPlatform->getAuthorizer($authCode); // 传入回调URI即可
    }

    /**
     * 接收回调
     */
    public  function openResCallback($appid = '')
    {
        $config = self::config();
        $openPlatform = Factory::openPlatform($config);
        $server = $openPlatform->server;
        // 处理授权成功事件
        $server->push(function ($message) {
            my::dingding('开放平台授权成功订单2：' . json_encode($message));
            $AuthorizerAppid = $message['AuthorizerAppid'];
            $AuthorizationCode = $message['AuthorizationCode'];
            $PreAuthCode = $message['PreAuthCode'];
            //{"AppId":"wxc4cdcebced6e215d","CreateTime":"1700750438","InfoType":"authorized","AuthorizerAppid":"wx408c5a916e0e03e8","AuthorizationCode":"queryauthcode@@@rkoRWtLMa_JAcNKCeNRQXuDVi0XMYK-gOdBl-8sX-iIBZBFwCT2PYi6LzZxbUuc_jDYbZnKj01CiNt664l7ACg","AuthorizationCodeExpiredTime":"1700754038","PreAuthCode":"preauthcode@@@BLgz9AAZASBF3rSFkea22aHpcdxYH3l_HQKuO6DAtOHPCwXqhX3lKT7DtS70Wns2bq0-dPfUl3OGZ4P0oVJ_QQ"}
            $config = self::config();
            $openPlatform = Factory::openPlatform($config);
            $ssss = $openPlatform->getAuthorizer($AuthorizerAppid);
            $type = isset($ssss['authorizer_info']['register_type']) ? '2' : '1';
            $new = [
                'nick_name' => $ssss['authorizer_info']['nick_name'],
                'wx_app_id' => $ssss['authorization_info']['authorizer_appid'],
                'service_type_info' => $ssss['authorizer_info']['service_type_info']['id'],
                'user_name' => $ssss['authorizer_info']['user_name'],
                'principal_name' => $ssss['authorizer_info']['principal_name'],
                'alias' => $ssss['authorizer_info']['alias'],
                'image' => isset($ssss['authorizer_info']['head_img']) ? $ssss['authorizer_info']['head_img'] : "",
                'signature' => $ssss['authorizer_info']['signature'],
                'qrcode_url' => $ssss['authorizer_info']['qrcode_url'],
                'authorizer_refresh_token' => $ssss['authorization_info']['authorizer_refresh_token'],
                'status' => $ssss['authorizer_info']['account_status'],
                'createtime' => time(),
            ];
            if ($type == 1) {
                $o =  db::table('fa_open_mp')->where('wx_app_id', $ssss['authorization_info']['authorizer_appid'])->find();
                if ($o) {
                    db::table('fa_open_mp')->where('id', $o['id'])->insert($new);
                } else {
                    db::table('fa_open_mp')->insert($new);
                }
            }

            my::dingding('开放平台用户订单2：' . json_encode($ssss));
            //  $url1 =  Wechat::handleAuthorize($auth_code);
        }, Guard::EVENT_AUTHORIZED);

        // 处理授权更新事件
        $server->push(function ($message) {
            my::dingding('开放平台授权更新订单2：' . json_encode($message));
            $config = self::config();
            $openPlatform = Factory::openPlatform($config);
            $AuthorizerAppid = isset($message['AuthorizerAppid']) ? $message['AuthorizerAppid'] : '';
            if ($AuthorizerAppid) {
                $ssss = $openPlatform->getAuthorizer($AuthorizerAppid);
            } else {
                $ssss = $message;
            }


            $type = isset($ssss['authorizer_info']['register_type']) ? '2' : '1';
            $new = [
                'nick_name' => $ssss['authorizer_info']['nick_name'],
                'wx_app_id' => $ssss['authorization_info']['authorizer_appid'],
                'service_type_info' => $ssss['authorizer_info']['service_type_info']['id'],
                'user_name' => $ssss['authorizer_info']['user_name'],
                'principal_name' => $ssss['authorizer_info']['principal_name'],
                'alias' => $ssss['authorizer_info']['alias'],
                'image' => isset($ssss['authorizer_info']['head_img']) ? $ssss['authorizer_info']['head_img'] : "",
                'signature' => $ssss['authorizer_info']['signature'],
                'qrcode_url' => $ssss['authorizer_info']['qrcode_url'],
                'authorizer_refresh_token' => $ssss['authorization_info']['authorizer_refresh_token'],
                'status' => $ssss['authorizer_info']['account_status'],
                'createtime' => time(),
            ];
            if ($type == 1) {
                $o =  db::table('fa_open_mp')->where('wx_app_id', $ssss['authorization_info']['authorizer_appid'])->find();
                if (!$o) {
                    db::table('fa_open_mp')->where('id', $o['id'])->insert($new);
                } else {
                    db::table('fa_open_mp')->insert($new);
                }
            }
        }, Guard::EVENT_UPDATE_AUTHORIZED);

        // 处理授权取消事件
        $server->push(function ($message) {
            my::dingding('开放平台授权取消订单2：' . json_encode($message));
            //{"AppId":"wxc4cdcebced6e215d","CreateTime":"1700750326","InfoType":"unauthorized","AuthorizerAppid":"wx408c5a916e0e03e8"}
        }, Guard::EVENT_UNAUTHORIZED);

        $server->push(function ($message) {
            my::dingding('第三方小程序注册订单2：' . json_encode($message));
            //{"AppId":"wxc4cdcebced6e215d","CreateTime":"1701012652","InfoType":"notify_third_fasteregister","status":"0","msg":"OK","appid":"wxd97631d5f808bda4","auth_code":"queryauthcode@@@eIaqKUBXWI2TTwRv10JQ0dprlnoZOGD-s-dJlBkTWD7aJFzK2owDYfrljLXwixIFrI-2_u-5ICZtgOSEp8Ph3g","info":{"name":"\u6cb3\u5357\u516b\u6069\u79d1\u6280\u6709\u9650\u516c\u53f8","code":"91411103MAD4J3KY1C","code_type":"1","legal_persona_wechat":"ppppue","legal_persona_name":"\u6768\u5175\u6d9b","component_phone":"18838000395"}}

            //{"AppId":"wxc4cdcebced6e215d","CreateTime":"1700750326","InfoType":"unauthorized","AuthorizerAppid":"wx408c5a916e0e03e8"}
        }, 'notify_third_fasteregister');
        //你可以通过以下方式拿到当前 verify_ticket 类：
        // $verifyTicket = $app->getVerifyTicket();
        // $input = file_get_contents('php://input');
        //  my::dingding('开放平台验证订单2：' . $input);
        // $verifyTicket->getTicket(); // strval
        // $account = $app->getAccount();

        // $account->getAppId();
        // $account->getSecret();
        // $account->getToken();
        // $account->getAesKey();

        return $server->serve();
    }
    /**
     * 公众号配置
     */
    public static function config_mp()
    {
        $config_open = [
            'app_id'   => 'wx6a20a1300ba9e158',
            'secret'   => '59c34f438a350e30fc08c002276e752b',
            //'response_type' => 'object',
            'token' => 'f1c242gdfhggfhghgh',
            'aes_key' => 'hPM9UCsg3Oie1yHeuO821z3DRhQBmYnFigLY1D23csk',
        ];
        return $config_open;
    }
    /**
     * 永久二维码
     */
    public function forever()
    {
        $config = self::config_mp();
        // $openPlatform = Factory::openPlatform($config);
        $app = Factory::officialAccount($config);
        //  $accessToken = $app->access_token;
        //$token = $accessToken->getToken(true); // token 数组  token['access_token'] 字符串
        //return $token;
        $result = $app->qrcode->forever(56);
        return json($result);
    }
    /**
     * 获取公众号h5配置
     */
    public static function buildConfig($url = 'https://hf.8nit.cn/')
    {
        $config = self::config_mp();
        // $openPlatform = Factory::openPlatform($config);
        $app = Factory::officialAccount($config);
        //  $accessToken = $app->access_token;
        //$token = $accessToken->getToken(true); // token 数组  token['access_token'] 字符串
        //return $token;
        $result = $app->qrcode->forever(56);
        $APIs = [
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'hideMenuItems'
        ];
        $app->jssdk->setUrl($url);
        $result =  $app->jssdk->buildConfig($APIs, $debug = true, $beta = false, $json = true);


        return $result;
    }

    /**
     * 临时二维码
     */
    public static function temporary($key = '5555', $arr = false)
    {
        $config = self::config_mp();
        // $openPlatform = Factory::openPlatform($config);
        $app = Factory::officialAccount($config);
        //  $accessToken = $app->access_token;
        //$token = $accessToken->getToken(true); // token 数组  token['access_token'] 字符串
        //return $token;
        $result = $app->qrcode->temporary($key, 60);
        if ($arr) {
            return $result;
        }
        return json_encode($result);
    }
    public  function tt()
    {
        $config = self::config_mp();
        $app = Factory::officialAccount($config);
        $user = $app->user->get('oEz4X6Xstlk8Yn1B7R8sc9qfe7B4');
        return json($user);
        //{"subscribe":1,"openid":"oEz4X6Xstlk8Yn1B7R8sc9qfe7B4","nickname":"","sex":0,"language":"zh_CN","city":"","province":"","country":"","headimgurl":"","subscribe_time":1700397321,"unionid":"ovQTh6p2aI_WTD79tfmZXNCLWGz4","remark":"","groupid":0,"tagid_list":[],"subscribe_scene":"ADD_SCENE_SEARCH","qr_scene":0,"qr_scene_str":""}
    }
    /**
     * 接收回调 公众号
     */
    public  function mpResCallback()
    {
        $input = file_get_contents('php://input');
        //  my::dingding('公众号通知订单1：' . $input);

        my::dingding('公众号通知订单3：' . json_encode(request()->request()));
        $config = self::config_mp();
        // $openPlatform = Factory::openPlatform($config);
        $app = Factory::officialAccount($config);
        $app->server->push(function ($message) {
            // $message['FromUserName'] // 用户的 openid
            // $message['MsgType'] // 消息类型：event, text....'
            //  my::dingding('公众号通知订单2：' . json_encode($message));
            if ($message['MsgType'] == 'event') { //事件
                if ($message['Event'] == 'SCAN') {
                    $FromUserName = $message['FromUserName'];
                    $config = self::config_mp();
                    $app = Factory::officialAccount($config);
                    $user = $app->user->get($FromUserName);
                    if (isset($user['unionid'])) {
                        $unionid = $user['unionid'];
                    } else {
                        $unionid = '';
                    }

                    if (isset($message['EventKey'])) {
                        $key = $message['EventKey'];
                        if (!$key) {
                            return "感谢您关注八恩科技官方公众号！";
                        }
                    } else {
                        return "感谢您关注八恩科技官方公众号！";
                    }
                    if (is_numeric($key)) {
                        $sssss =  db::table('fa_admin')->where('openid', $FromUserName)->find();
                        if ($sssss) {
                            return "此微信已绑定其他账号，无需再次绑定";
                        }
                        db::table('fa_admin')->where('id', $key)->update(['openid' => $FromUserName, 'unionid' => $unionid]);
                        $admin = db::table('fa_mplogin_bind')->where('admin_id', $key)->find();
                        if (!$admin) {
                            db::table('fa_mplogin_bind')->insert(['admin_id' => $key, 'mp_openid' => $FromUserName, 'createtime' => time()]);
                        }
                        return "绑定成功,感谢您的使用";
                        //fa_mplogin_bind
                    }

                    $key_info = Key::getKey($key);
                    $token = cache::get($key_info->key . "login_token");
                    if (!$token) {
                        return "登录失败，可能未绑定微信";
                    }
                    //$token = Session::pull("login_token");

                    $key_info->state = 2;
                    $key_info->login_token = $token;
                    $key_info->scan_openid = $FromUserName;
                    $key_info->save();
                    Cache::set($token, $token, 10);
                    return "登录成功,感谢您的使用";
                } elseif ($message['Event'] == 'subscribe') {
                    return "感谢您关注八恩科技官方公众号！";
                }
            }
            //{"ToUserName":"gh_21a6b08e62a3","FromUserName":"oEz4X6YvaVeINTvQ31UIsBO3A1w8","CreateTime":"1700921773","MsgType":"event","Event":"SCAN","EventKey":"12","Ticket":"gQF78TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAybl81QTFMai1jbkYxMDAwME0wM1AAAgSz1mFlAwQAAAAA"}

            return "";
        });
        //return request()->request('echostr');
        $response = $app->server->serve();
        $response->send();
        //return $response;
    }
    /**
     * 临时二维码
     */
    public static function send($openid)
    {
        $config = self::config_mp();
        // $openPlatform = Factory::openPlatform($config);
        $app = Factory::officialAccount($config);
        $app->template_message->send([
            'touser' => $openid,
            'template_id' => '06CTh6w-iU8RUEnnksp9TUvER3-XXM6V11hhXINXH_U',
            // 'url' => 'https://easywechat.com',
            'miniprogram' => [
                'appid' => 'xxxxxxx',
                'pagepath' => 'pages/xxx',
            ],
            'data' => [
                'key1' => 'VALUE',
                'key2' => 'VALUE2',

            ],
        ]);
    }

    /**
     * xcx配置
     */
    public static function config_xcx()
    {
        $config_open = [
            'app_id'   => 'wxf070218e9dcfd347',
            'secret'   => '029b0266ea96d4d9cbe6983aa21f49f0',
            //'response_type' => 'object',
            // 'token' => 'f1c242gdfhggfhghgh',
            // 'aes_key' => 'hPM9UCsg3Oie1yHeuO821z3DRhQBmYnFigLY1D23csk',
        ];
        return $config_open;
    }

    public static function xcxlogin($code)
    {
        $config = self::config_xcx();
        $app = Factory::miniProgram($config);
        return $app->auth->session($code);
    }
    public static function getPhoneNumber($code)
    {
        $config = self::config_xcx();
        $app = Factory::miniProgram($config);
        $response = $app->httpPostJson('/wxa/business/getuserphonenumber', [
            "code" => $code,
        ]);
        return $response;
        //$decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
        // return $app->auth->session($code);
    }
    /**
     * 微信账本
     */
    public  function wxzb()
    {
        $add_money = request()->request('money');
        $remark = request()->request('remark');
        $order = request()->request('order');
        my::dingding('扫码订单2：' . json_encode(request()->request()));
        if ($remark) {
            $orderddd =  db::table('fa_admin_money')->where('orderPc', $order)->find();
            if ($orderddd) {
                return 'chongfu';
            }

            $admin =  db::table('fa_admin')->where('mobile', $remark)->find();
            $money = $admin['money'];
            $new_money = round($money + $add_money, 2);
            db::table('fa_admin')->where('mobile', $remark)->update(['money' => $money]);

            money::create(['admin_id' => $admin['id'], 'type' => 1, 'money' => $add_money, 'before' => $money, 'after' => $new_money, 'memo' => '扫码充值', 'type1' => 2, 'orderPc' => $order]); //交易方式:1=支出,2=收入,3=暂未归类
        } else {
        }
        return 'success';
        //https://mch.8nit.cn/api/wechat/wxzb?money=收款金额&remark=收款备注&order=收款订单号
    }

    /**
     * xcx配置
     */
    public static function config_xcx1()
    {
        $config_open = [
            'app_id'   => 'wx6185120db35f85a4',
            'secret'   => 'dfb5bc64a1073572338edfc72a8f609a',
        ];
        return $config_open;
    }

    public static function xcxlogin1($code)
    {
        $config = self::config_xcx1();
        $app = Factory::miniProgram($config);
        return $app->auth->session($code);
    }
}
